package org.springframework.context.event;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * @Name SimpleApplicationEventMulticaster
 * @Description: 注册事件监听器和发布事件的 [实现] 类
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-03-21 15:49:55
 **/
public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {

    public SimpleApplicationEventMulticaster(BeanFactory beanFactory) {
        setBeanFactory(beanFactory);
    }

    @Override
    public void multicastEvent(ApplicationEvent event) {
        applicationListeners.forEach(listener -> {
            if (supportsEvent(listener, event)) {
                listener.onApplicationEvent(event);
            }
        });
    }

    /**
     * 判断事件监听器是否对该事件感兴趣
     *
     * @param listener 事件监听器
     * @param event    事件
     * @return boolean
     * @version v1.0.0
     * @author lichao
     * @date 2024-03-21 15:53:49
     */
    protected boolean supportsEvent(ApplicationListener<ApplicationEvent> listener, ApplicationEvent event) {
        Type type = listener.getClass().getGenericInterfaces()[0];
        Type actualTypeArgument = ((ParameterizedType) type).getActualTypeArguments()[0];
        String className = actualTypeArgument.getTypeName();
        Class<?> eventClassName;
        try {
            eventClassName = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new BeansException("错误的事件类名称：" + className);
        }
        return eventClassName.isAssignableFrom(event.getClass());
    }
}

